import 'package:flutter/foundation.dart';

import '../models/models.dart';
import '../constants/constants.dart';
import '../services/services.dart';

/// Mock数据类
/// 提供测试用的音乐、播放列表、播放历史等数据
class MockData {
  /// 获取Mock音乐列表
  static List<Music> getMockMusicList() {
    return [
      Music(
        id: 'mock_1',
        title: '星空下的旋律',
        artist: '梦幻乐队',
        album: '星空物语',
        filePath:
            'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3',
        duration: const Duration(minutes: 3, seconds: 45).inMilliseconds,
        fileSize: 5242880, // 5MB
        year: 2023,
        genre: '流行',
        coverArt: AppAssets.defaultCoverPath,
        isFavorite: true,
        playCount: 15,
        createdAt: DateTime.now().subtract(const Duration(days: 30)),
        updatedAt: DateTime.now().subtract(const Duration(hours: 2)),
      ),
      Music(
        id: 'mock_2',
        title: '夜色温柔',
        artist: '月光歌手',
        album: '夜曲集',
        filePath:
            'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3',
        duration: const Duration(minutes: 4, seconds: 12).inMilliseconds,
        fileSize: 6291456, // 6MB
        year: 2022,
        genre: '民谣',
        coverArt: AppAssets.defaultCoverPath,
        isFavorite: false,
        playCount: 8,
        createdAt: DateTime.now().subtract(const Duration(days: 25)),
        updatedAt: DateTime.now().subtract(const Duration(days: 1)),
      ),
      Music(
        id: 'mock_3',
        title: '科技之光',
        artist: '未来音响',
        album: '数字时代',
        filePath:
            'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3',
        duration: const Duration(minutes: 3, seconds: 28).inMilliseconds,
        fileSize: 4718592, // 4.5MB
        year: 2024,
        genre: '电子',
        coverArt: AppAssets.defaultCoverPath,
        isFavorite: true,
        playCount: 22,
        createdAt: DateTime.now().subtract(const Duration(days: 15)),
        updatedAt: DateTime.now().subtract(const Duration(minutes: 30)),
      ),
      Music(
        id: 'mock_4',
        title: '城市节拍',
        artist: '都市乐团',
        album: '城市印象',
        filePath:
            'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-4.mp3',
        duration: const Duration(minutes: 3, seconds: 55).inMilliseconds,
        fileSize: 5767168, // 5.5MB
        year: 2023,
        genre: '摇滚',
        coverArt: AppAssets.defaultCoverPath,
        isFavorite: false,
        playCount: 12,
        createdAt: DateTime.now().subtract(const Duration(days: 20)),
        updatedAt: DateTime.now().subtract(const Duration(hours: 6)),
      ),
      Music(
        id: 'mock_5',
        title: '宁静致远',
        artist: '禅音工作室',
        album: '心灵净土',
        filePath:
            'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-5.mp3',
        duration: const Duration(minutes: 5, seconds: 18).inMilliseconds,
        fileSize: 7340032, // 7MB
        year: 2021,
        genre: '轻音乐',
        coverArt: AppAssets.defaultCoverPath,
        isFavorite: true,
        playCount: 35,
        createdAt: DateTime.now().subtract(const Duration(days: 45)),
        updatedAt: DateTime.now().subtract(const Duration(hours: 12)),
      ),
    ];
  }

  /// 获取Mock播放列表
  static List<Playlist> getMockPlaylists() {
    return [
      Playlist(
        id: 'playlist_1',
        name: '我的最爱',
        description: '收藏的经典歌曲',
        coverImage: AppAssets.defaultCoverPath,
        musicIds: ['mock_1', 'mock_3', 'mock_5'],
        createdAt: DateTime.now().subtract(const Duration(days: 30)),
        updatedAt: DateTime.now().subtract(const Duration(days: 2)),
      ),
      Playlist(
        id: 'playlist_2',
        name: '夜晚时光',
        description: '适合夜晚聆听的音乐',
        coverImage: AppAssets.defaultCoverPath,
        musicIds: ['mock_2', 'mock_5'],
        createdAt: DateTime.now().subtract(const Duration(days: 20)),
        updatedAt: DateTime.now().subtract(const Duration(days: 5)),
      ),
      Playlist(
        id: 'playlist_3',
        name: '工作专注',
        description: '提高工作效率的背景音乐',
        coverImage: AppAssets.defaultCoverPath,
        musicIds: ['mock_3', 'mock_4'],
        createdAt: DateTime.now().subtract(const Duration(days: 15)),
        updatedAt: DateTime.now().subtract(const Duration(days: 1)),
      ),
    ];
  }

  /// 获取Mock播放历史
  static List<PlayHistory> getMockPlayHistory() {
    final now = DateTime.now();
    return [
      PlayHistory(
        id: 'history_1',
        musicId: 'mock_3',
        playedAt: now.subtract(const Duration(minutes: 30)),
        playDuration: const Duration(minutes: 3, seconds: 28).inMilliseconds,
        completed: true,
        progress: 1.0,
      ),
      PlayHistory(
        id: 'history_2',
        musicId: 'mock_1',
        playedAt: now.subtract(const Duration(hours: 2)),
        playDuration: const Duration(minutes: 2, seconds: 15).inMilliseconds,
        completed: false,
        progress: 0.6,
      ),
      PlayHistory(
        id: 'history_3',
        musicId: 'mock_5',
        playedAt: now.subtract(const Duration(hours: 6)),
        playDuration: const Duration(minutes: 5, seconds: 18).inMilliseconds,
        completed: true,
        progress: 1.0,
      ),
      PlayHistory(
        id: 'history_4',
        musicId: 'mock_2',
        playedAt: now.subtract(const Duration(hours: 12)),
        playDuration: const Duration(minutes: 4, seconds: 12).inMilliseconds,
        completed: true,
        progress: 1.0,
      ),
      PlayHistory(
        id: 'history_5',
        musicId: 'mock_4',
        playedAt: now.subtract(const Duration(days: 1)),
        playDuration: const Duration(minutes: 1, seconds: 45).inMilliseconds,
        completed: false,
        progress: 0.45,
      ),
      PlayHistory(
        id: 'history_6',
        musicId: 'mock_3',
        playedAt: now.subtract(const Duration(days: 2)),
        playDuration: const Duration(minutes: 3, seconds: 28).inMilliseconds,
        completed: true,
        progress: 1.0,
      ),
      PlayHistory(
        id: 'history_7',
        musicId: 'mock_1',
        playedAt: now.subtract(const Duration(days: 3)),
        playDuration: const Duration(minutes: 3, seconds: 45).inMilliseconds,
        completed: true,
        progress: 1.0,
      ),
    ];
  }

  /// 获取Mock用户设置
  static UserSettings getMockUserSettings() {
    return UserSettings(
      id: 'mock_settings',
      themeMode: ThemeMode.dark,
      volume: 0.8,
      playMode: PlayMode.sequence,
      audioQuality: AudioQuality.high,
      lyricsEnabled: true,
      crossfadeEnabled: true,
      sleepTimerEnabled: false,
      sleepTimerDuration: 0,
      hapticFeedbackEnabled: true,
      lockScreenControlEnabled: true,
      updatedAt: DateTime.now(),
    );
  }

  /// 获取Mock主题配置
  static List<ThemeConfig> getMockThemeConfigs() {
    return [
      ThemeConfig.techDark(),
      ThemeConfig.techLight(),
      ThemeConfig(
        id: 'purple_theme',
        themeName: '紫色梦幻',
        primaryColor: '#9C27B0',
        accentColor: '#E91E63',
        backgroundColor: '#1A0E2E',
        surfaceColor: '#2D1B3D',
        isDark: true,
        createdAt: DateTime.now().subtract(const Duration(days: 10)),
      ),
      ThemeConfig(
        id: 'green_theme',
        primaryColor: '#4CAF50',
        accentColor: '#8BC34A',
        backgroundColor: '#0E1A0E',
        surfaceColor: '#1B2D1B',
        isDark: true,
        createdAt: DateTime.now().subtract(const Duration(days: 5)),
        themeName: '自然绿意',
      ),
    ];
  }

  /// 获取Mock播放统计
  static PlayStatistics getMockPlayStatistics() {
    return PlayStatistics(
      mostPlayedMusicIds: ['mock_5', 'mock_3', 'mock_1'], // 添加最常播放音乐ID列表
      totalPlayTime: const Duration(hours: 25, minutes: 30).inMilliseconds,
      totalPlayCount: 92,
      todayPlayTime: const Duration(hours: 2, minutes: 15).inMilliseconds,
      todayPlayCount: 8,

      id: 'mock_statistics',
      recentlyPlayedMusicIds: [],
      updatedAt: DateTime.now(),
    );
  }

  /// 初始化Mock数据到数据库
  static Future<void> initializeMockData({
    required DatabaseService databaseService,
    required HiveService hiveService,
  }) async {
    try {
      // 清空现有数据
      await databaseService.clearAllData();
      await hiveService.clearAllCache();

      // 插入Mock音乐数据
      final musicList = getMockMusicList();
      for (final music in musicList) {
        await databaseService.insertMusic(music);
        await hiveService.saveMusic(music);
      }

      // 插入Mock播放列表数据
      final playlists = getMockPlaylists();
      for (final playlist in playlists) {
        await databaseService.insertPlaylist(playlist);
      }

      // 插入Mock播放历史数据
      final playHistory = getMockPlayHistory();
      for (final history in playHistory) {
        await databaseService.insertPlayHistory(history);
      }

      // 保存Mock用户设置
      final userSettings = getMockUserSettings();
      await hiveService.saveUserSettings(userSettings);

      // 保存Mock主题配置
      final themeConfigs = getMockThemeConfigs();
      for (final theme in themeConfigs) {
        await hiveService.saveThemeConfig(theme);
      }

      // 更新播放统计
      final statistics = getMockPlayStatistics();
      await databaseService.insertOrUpdatePlayStatistics(statistics);

      debugPrint('Mock数据初始化完成');
    } catch (e) {
      debugPrint('Mock数据初始化失败: $e');
      rethrow;
    }
  }

  /// 检查是否需要初始化Mock数据
  static Future<bool> shouldInitializeMockData(
      DatabaseService databaseService) async {
    try {
      final musicList = await databaseService.getAllMusic();
      return musicList.isEmpty;
    } catch (e) {
      return true; // 如果查询失败，假设需要初始化
    }
  }

  /// 获取随机Mock音乐
  static Music getRandomMockMusic() {
    final musicList = getMockMusicList();
    musicList.shuffle();
    return musicList.first;
  }

  /// 获取Mock收藏音乐列表
  static List<Music> getMockFavoriteMusic() {
    return getMockMusicList().where((music) => music.isFavorite).toList();
  }

  /// 获取Mock最近播放音乐列表
  static List<Music> getMockRecentMusic() {
    final musicList = getMockMusicList();
    musicList.sort((a, b) => b.updatedAt.millisecondsSinceEpoch
        .compareTo(a.updatedAt.millisecondsSinceEpoch));
    return musicList.take(3).toList();
  }

  /// 获取Mock热门音乐列表
  static List<Music> getMockPopularMusic() {
    final musicList = getMockMusicList();
    musicList.sort((a, b) => b.playCount.compareTo(a.playCount));
    return musicList.take(3).toList();
  }

  /// 生成Mock播放历史（按时间分组）
  static Map<String, List<PlayHistory>> getMockPlayHistoryGrouped() {
    final history = getMockPlayHistory();
    final Map<String, List<PlayHistory>> grouped = {};

    for (final item in history) {
      final date = DateTime(item.playedAt?.year ?? 0, item.playedAt?.month ?? 0,
          item.playedAt?.day ?? 0);
      final dateKey = _formatDateKey(date);

      if (!grouped.containsKey(dateKey)) {
        grouped[dateKey] = [];
      }
      grouped[dateKey]!.add(item);
    }

    return grouped;
  }

  /// 格式化日期键
  static String _formatDateKey(DateTime date) {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    final yesterday = today.subtract(const Duration(days: 1));

    if (date == today) {
      return '今天';
    } else if (date == yesterday) {
      return '昨天';
    } else {
      return '${date.month}月${date.day}日';
    }
  }

  /// 获取Mock搜索建议
  static List<String> getMockSearchSuggestions() {
    return [
      '星空下的旋律',
      '夜色温柔',
      '科技之光',
      '城市节拍',
      '宁静致远',
      '梦幻乐队',
      '月光歌手',
      '未来音响',
      '都市乐团',
      '禅音工作室',
      '流行',
      '民谣',
      '电子',
      '摇滚',
      '轻音乐',
    ];
  }
}
